<template>
  <el-row :gutter="16">
    <el-col :span="8">
      <div class="statistic-card">
        <el-statistic :value="userTotal + '人'">
          <template #title>
            <div style="display: inline-flex; align-items: center">
              用户总数
              <el-tooltip effect="dark" content="用户总数" placement="top">
                <el-icon style="margin-left: 4px" :size="12">
                  <Warning />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
        </el-statistic>
        <!-- <div class="statistic-footer">
          <div class="footer-item">
            <span>今日新增用户数</span>
            <span class="green">
              {{ newUser }}
              <el-icon>
                <CaretTop />
              </el-icon>
            </span>
          </div>
        </div> -->
      </div>
    </el-col>
    <el-col :span="8">
      <div class="statistic-card">
        <el-statistic :value="publicity + '条'">
          <template #title>
            <div style="display: inline-flex; align-items: center">
              公告总数
              <el-tooltip effect="dark" content="公告总数" placement="top">
                <el-icon style="margin-left: 4px" :size="12">
                  <Warning />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
        </el-statistic>
        <!-- <div class="statistic-footer">
          <div class="footer-item">
            <span>month on month</span>
            <span class="red">
              12%
              <el-icon>
                <CaretBottom />
              </el-icon>
            </span>
          </div>
        </div> -->
      </div>
    </el-col>
    <el-col :span="8">
      <div class="statistic-card">
        <el-statistic :value="money + '元'" title="New transactions today">
          <template #title>
            <div style="display: inline-flex; align-items: center">
              总销量
            </div>
          </template>
        </el-statistic>
        <!-- <div class="statistic-footer">
          <div class="footer-item">
            <span>than yesterday</span>
            <span class="green">
              16%
              <el-icon>
                <CaretTop />
              </el-icon>
            </span>
          </div>
          <div class="footer-item">
            <el-icon :size="14">
              <ArrowRight />
            </el-icon>
          </div>
        </div> -->
      </div>
    </el-col>
  </el-row>

  <!-- 时间选择器 -->

  <el-form :inline="true" :model="dateForm" class="demo-form-inline">
    <el-form-item label="日期">
      <el-date-picker v-model="dataTime" type="daterange" range-separator="到" start-placeholder="开始时间"
        end-placeholder="结束时间" :size="size" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">搜索</el-button>
    </el-form-item>
  </el-form>

  <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
  <div id="main" style="width: 600px;height:400px;"></div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { onMounted } from 'vue';
import * as echarts from 'echarts';

import axios from 'axios';



const userInfo = ref({});
const userTotal = ref(0);
const newUser = ref(0);
const publicity = ref(0);
const money = ref(0);
//时间
const dateForm = ref('')

const size = ref('default')

const dataTime = ref('')

const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

//图表数据
var option;

option = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], // x轴
      axisTick: {
        alignWithLabel: true
      }
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: '销售额',
      type: 'bar',
      barWidth: '60%',
      data: [10, 52, 200, 334, 390, 330, 220] //y轴
    }
  ]
};

//设置x轴数据
const getXAxis = () => {
  // console.log(dataTime._rawValue[0]+dataTime._rawValue[1]);
  const start = dataTime._rawValue[0]
  const end = dataTime._rawValue[1]
  const startDate = new Date(start)
  const endDate = new Date(end)
  const x = generateDateRange(startDate, endDate)
  // console.log(x);
  option.xAxis[0].data = x
  // console.log(option.xAxis[0].data);
}
//格式化x轴数据
function generateDateRange(startDateObj, endDateObj) {
  // 验证传入的参数是否为 Date 对象
  if (!(startDateObj instanceof Date) || !(endDateObj instanceof Date)) {
    throw new Error('传入的参数必须为 Date 对象');
  }

  const startDate = startDateObj;
  const endDate = endDateObj;

  // 确保 startDate 小于等于 endDate
  if (startDate > endDate) {
    throw new Error('开始日期必须小于或等于结束日期');
  }

  const dateRange = [];

  // 定义一个变量来追踪当前日期（这里不需要再次使用 new Date()）
  let currentDate = new Date(startDate); // 实际上可以直接用 startDate，但为了保持一致性，这里保留 new Date()
  currentDate.setHours(0, 0, 0, 0); // 确保时间是 00:00:00

  // 循环直到当前日期超过 endDate（不包含 endDate 的下一天）
  while (currentDate <= endDate) {
    // 格式化当前日期为 "YYYY-MM-DD"
    // 使用 toLocaleDateString 可以根据本地时区格式化日期，但我们需要的是 UTC 日期
    // 因此，我们可以手动构建日期字符串，或者使用 getFullYear, getMonth, getDate 方法
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
    const day = String(currentDate.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;

    dateRange.push(formattedDate);

    // 将当前日期增加一天（这里会自动处理月份和年份的变更）
    currentDate.setDate(currentDate.getDate() + 1);
  }

  return dateRange;
}


//获取y轴数据
const getSeries = () => {
  const start = dataTime._rawValue[0]
  const end = dataTime._rawValue[1]
  const startDate = new Date(start)
  const endDate = new Date(end)
  // console.log(startDate);
  // console.log(endDate);
  //发送时间对象给后端获取当天总额更新图表
  axios.get('/courseOrder/getMoneyByTime', {
    params: {
      startDate: startDate,
      endDate: endDate
    }
  }).then(res => {
    option.series[0].data = []
    option.xAxis[0].data = []
    // console.log(res.data.data);
    // console.log(res.data.data[0].q);
    for (let i = 0; i < res.data.data.length; i++) {
      option.series[0].data.push(res.data.data[i].q)
      option.xAxis[0].data.push(res.data.data[i].d) 
    }
    updateChart();
  }).catch(err => {
    console.log('数据有误');
  })
}

const onSubmit = async () => {
  await getXAxis(); 
  await getSeries();
};


//获取所用用户总数
const getSysUserTotal = () => {
  axios.get('/SystemUser/getTotal').then(res => {
    // console.log(res.data.data);
    userTotal.value = res.data.data;
  }).catch(err => {
    // console.log(err);
  })
  axios.get('/user/getTotal').then(res => {
    userTotal.value = ((res.data.data) + (userTotal.value));
  })
}
//获取公告总数
const getPublicityTotal = () => {
  axios.get('/publicity/getTotal').then(res => {
    // console.log(res.data.data);
    publicity.value = res.data.data;
  })
}
//获取总销量
const getMoneyTotal = () => {
  axios.get('/courseOrder/getTotalMoney').then(res => {
    // console.log(res.data.data);
    money.value = res.data.data;
  })
}

const getCurrentTime = ()=>{
  const now = new Date();
  const pastDate = new Date(now); // 复制当前时间
  pastDate.setDate(now.getDate() - 7); // 减去 7 天
  // console.log("当前时间:", now.toString());
  // console.log("减去 7 天后的时间:", pastDate.toString());
  dataTime._rawValue = []
  dataTime._rawValue.push(pastDate)
  dataTime._rawValue.push(now)
}

onMounted(() => {
  getUserInfo();
  getSysUserTotal()
  getPublicityTotal()
  getMoneyTotal()
  

  //加载图表
  showChart()


})
var chartDom = null
var myChart = null
//图表数据显示
const showChart = () => {
  //要放在onMounted中
  // 基于准备好的dom，初始化echarts实例
  chartDom = document.getElementById('main');
  myChart = echarts.init(chartDom);
  //首次数据
  getCurrentTime()
  onSubmit()
  // 使用刚指定的配置项和数据显示图表。
  option && myChart.setOption(option);
}

//动态图表数据更新
const updateChart = () => {
  myChart.setOption(option);
}



//获取当前用户信息
const getUserInfo = () => {
  userInfo.value = localStorage.getItem('userInfo');
  // console.log(userInfo.value);
  userInfo.value = JSON.parse(userInfo.value);
  // console.log(userInfo.value.role);
}
</script>
<style scoped>
.demo-datetime-picker-icon {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: stretch;
}

.demo-datetime-picker-icon .block {
  padding: 30px 0;
  text-align: center;
}

.line {
  width: 1px;
  background-color: var(--el-border-color);
}

.chart {
  height: 400px;
}

:global(h2#card-usage ~ .example .example-showcase) {
  background-color: var(--el-fill-color) !important;
}

.el-statistic {
  --el-statistic-content-font-size: 28px;
}

.statistic-card {
  height: 100%;
  padding: 20px;
  border-radius: 4px;
  background-color: var(--el-bg-color-overlay);
}

.statistic-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-top: 16px;
}

.statistic-footer .footer-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistic-footer .footer-item span:last-child {
  display: inline-flex;
  align-items: center;
  margin-left: 4px;
}

.green {
  color: var(--el-color-success);
}

.red {
  color: var(--el-color-error);
}
</style>